package com.zichen.pr.system.controller;

import com.zichen.pr.common.constant.UserConstants;
import com.zichen.pr.common.core.controller.BaseController;
import com.zichen.pr.common.core.domain.entity.SysRole;
import com.zichen.pr.common.core.domain.entity.SysUser;
import com.zichen.pr.common.core.domain.result.Result;
import com.zichen.pr.common.core.page.TableDataInfo;
import com.zichen.pr.framework.web.service.TokenService;
import com.zichen.pr.system.service.SysPostService;
import com.zichen.pr.system.service.SysRoleService;
import com.zichen.pr.system.service.SysUserService;
import com.zichen.pr.util.SecurityUtils;
import com.zichen.pr.util.StringUtils;
import com.zichen.pr.util.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: zichen
 * @description: 用户信息
 * @author: rzhang
 * @create: 2021-04-23 07:59
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    @Autowired
    private TokenService tokenService;

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysPostService sysPostService;


    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = sysUserService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public Result getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        Result ajax = Result.success();
        List<SysRole> roles = sysRoleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", sysPostService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            ajax.put(Result.DATA_TAG, sysUserService.selectUserById(userId));
            ajax.put("postIds", sysPostService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysRoleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @PostMapping
    public Result add(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(sysUserService.checkUserNameUnique(user.getUserName()))) {
            return Result.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(user))) {
            return Result.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(sysUserService.checkEmailUnique(user))) {
            return Result.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(sysUserService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping
    public Result edit(@Validated @RequestBody SysUser user) {
        sysUserService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(user))) {
            return Result.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(sysUserService.checkEmailUnique(user))) {
            return Result.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(sysUserService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @DeleteMapping("/{userIds}")
    public Result remove(@PathVariable Long[] userIds) {
        return toAjax(sysUserService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @PutMapping("/resetPwd")
    public Result resetPwd(@RequestBody SysUser user) {
        sysUserService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(sysUserService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping("/changeStatus")
    public Result changeStatus(@RequestBody SysUser user) {
        sysUserService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(sysUserService.updateUserStatus(user));
    }

    /**
     * excel文件上传数据
     */
    //@PreAuthorize("@ss.hasPermi('system:user:edit')")
    //@PostMapping("/importData")
    public Result importData(MultipartFile file) throws Exception {

        //其中sysuser需要修改加上注解@Excel(name="表头")

        ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);

        List<SysUser> users= util.importExcel(file.getInputStream());

        return toAjax(true);
    }
}
